<template>
  <div id="user">
    <header>
      <ul id="right">
        <li v-if="JSON.stringify( this.$store.state.userLoginMsg) == '{}' ">
          <span @click="$store.state.loginDialog = true">登录</span>|
          <span @click="dialogTableVisible = true">注册</span>
        </li>

        <li v-if="JSON.stringify(this.$store.state.userLoginMsg) != '{}' ">
          欢迎&emsp;
          <span style="color:red; width:40px" @click="layout">{{userLoginMsg.userName}}</span>
        </li>
        <li @click="$router.push('/order')">我的订单</li>
        <li @click="$router.push('/collect')">我的收藏</li>
        <li @click="$router.push('/shoppingCart')">
          <i class="el-icon-shopping-cart-full"></i>
          购物车({{this.$store.getters.getNum}})
        </li>
      </ul>
    </header>
    <!-- //用户注册用到的弹出框-->
    <el-dialog title="注册" :visible.sync="dialogTableVisible">
      <el-form :model="Registerobj" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input
            autocomplete="off"
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="Registerobj.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            autocomplete="off"
            prefix-icon="el-icon-view"
            placeholder="请输入密码"
            v-model="Registerobj.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password1">
          <el-input
            autocomplete="off"
            prefix-icon="el-icon-view"
            placeholder="请再次请输入密码"
            v-model="Registerobj.password1"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="gettRegister('ruleForm')">登录</el-button>
      </div>
    </el-dialog>
    <login></login>
  </div>
</template>

<script>
import Api from "@/api/User.js";
import { Notification } from "element-ui";
import { mapState, mapMutations } from "vuex";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (userNameRule.test(value)) {
        //判断数据库中是否已经存在该用户名
        Api.getFindUserName({ userName: this.Registerobj.username })
          .then(res => {
            console.log(res);

            // “001”代表用户名不存在，可以注册
            if (res.data.code == "001") {
              this.$refs.ruleForm.validateField("checkPass");
              return callback();
            } else {
              return callback(new Error(res.data.msg));
            }
          })
          .catch(err => {
            return Promise.reject(err);
          });
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    // 确认密码的校验方法
    let validateConfirmPass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入确认密码"));
      }
      // 校验是否以密码一致
      if (
        this.Registerobj.password != "" &&
        value === this.Registerobj.password
      ) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("两次输入的密码不一致"));
      }
    };
    //这里存放数据
    return {
      dialogTableVisible: false, //登录弹出框开关
      Registerobj: {
        username: "",
        password: "",
        password1: ""
      }, //注册用到的值
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        username: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        password1: [{ validator: validateConfirmPass, trigger: "blur" }]
      }
    };
  },
  //计算属性 类似于data概念
  computed: {
    ...mapState(["userLoginMsg"])
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    ...mapMutations(["layout"]),
    //用户注册
    gettRegister(ruleForm) {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs.ruleForm.validate(valid => {
        //如果通过校验开始注册
        if (valid) {
          var obj = {
            userName: this.Registerobj.username,
            password: this.Registerobj.password
          };
          Api.getRegister(obj)
            .then(res => {
              // “001”代表注册成功，其他的均为失败
              if (res.data.code === "001") {
                // 隐藏注册组件
                this.dialogTableVisible = false;
                // 弹出通知框提示注册成功信息
                Notification.success({ title: "成功", message: "注册成功" });
              } else {
                // 弹出通知框提示注册失败信息
                Notification.success({ title: "失败", message: "注册失败" });
              }
            })
            .catch(err => {
              return Promise.reject(err);
            });
        } else {
          return false;
        }
      });
    }
    //用户登录
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
#user {
  width: 100%;
  height: 100%;
  header {
    padding: 0 142px;
    width: 100%;
    height: 40px;
    background: #303030;
    display: flex;
    flex-direction: row-reverse;
    #right {
      width: 360px;
      height: 100%;
      padding-right: 56px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      li {
        list-style: none;
        font-size: 12px;
        color: #7c838d;
        font-weight: 700;
        &:nth-of-type(1) {
          margin-right: 10px;
          // border: 1px solid #000;
          display: flex;
          justify-content: space-between;
          align-items: center;
          span:hover {
            color: white;
          }
          span {
            &:nth-of-type(1) {
              margin-right: 4px;
            }
            &:nth-of-type(2) {
              margin-left: 4px;
            }
          }
        }
        &:nth-of-type(2):hover,
        &:nth-of-type(3):hover {
          color: white;
        }
        &:nth-of-type(4) {
          width: 110px;
          height: 100%;
          text-align: center;
          line-height: 40px;
          background: #363636;
          &:hover {
            background: red;
            color: white;
          }
        }
      }
    }
  }
}
</style>